package com.quasar.hpatient.view.prescription;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.custommodel.Alarm;
import com.quasar.hpatient.model.custommodel.AllprescriptionDataBean;
import com.quasar.hpatient.model.custommodel.Prescription;
import com.quasar.hpatient.model.custommodel.TemperatureTableItem;
import com.quasar.hpatient.model.event.UpdateEvent;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.litePalmodel.DoseModedb;
import com.quasar.hpatient.model.litePalmodel.DosePerioddb;
import com.quasar.hpatient.model.litePalmodel.MedicineInfodb;
import com.quasar.hpatient.model.medicalmodel.ClonePrescriptionData;
import com.quasar.hpatient.model.medicalmodel.PrescriptionDayData;
import com.quasar.hpatient.onInterface.OnPrescriptionListener;
import com.quasar.hpatient.presenter.PrescriptionPresenter;
import com.quasar.hpatient.utils.AlarmTime;
import com.quasar.hpatient.utils.DateUtil;
import com.quasar.hpatient.utils.OutliersValues;
import com.quasar.hpatient.utils.TimeZoneUtil;
import com.quasar.hpatient.utils.UrlUtils;
import com.quasar.hpatient.widget.SelectWidget;
import com.quasar.hpatient.widget.Widget_Alarm_Item;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OptionsItem;
import org.androidannotations.annotations.OptionsMenu;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;
import org.litepal.crud.DataSupport;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

/**
 * 添加药单
 */
@OptionsMenu(R.menu.menu_submit)
@EActivity(R.layout.activity_add_prescription)
public class AddPrescriptionActivity extends BaseActivity implements OnPrescriptionListener, AdapterView.OnItemClickListener, Widget_Alarm_Item.OnRemove {

    PrescriptionPresenter prescriptionPresenter;
    List<MedicineInfodb> medicineInfoList;//药品信息
    ArrayAdapter<MedicineInfodb> medicineAdapter;
    ArrayAdapter<String> Adapter;
    //记录药品名称id
    int medicineId = 0;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //服药方式
    List<DoseModedb> doseModeList = new ArrayList<>();
    String[] record_doseMode;
    //服药周期
    List<DosePerioddb> dosePeriodList = new ArrayList<>();
    String[] dosePeriod;
    private Alarm alarm = new Alarm();
    //记录服药时间
    List<String> strings = new ArrayList<>();
    //如何服药
    DoseModedb doseModedb;
    //服药时长
    DosePerioddb dosePeriodInfo;

    //获取选中的药品对象
    MedicineInfodb medicineInfo;
    //获取详情的json
    String json;
    StringBuffer statsTimeBuffer = new StringBuffer();
    //保存克隆id
    String TimeCloneDataId = null;

    String getID;
    String getTimeLen;
    String getPackages;
    String getPlid;

    String isdoseMode, fsdoseMode, olddoseModename;  //判断是否 如何服药
    String isdosePeriod, fsdosePeriod, olddosename;  //判断是否修改了 服药天数；
    String isdoseName;  //判断规格是否修改


    //记录当前药单数据
    @Extra
    PrescriptionDayData.ListBean ListPrescription;

    @Extra
    ArrayList<AllprescriptionDataBean> beanList;  //传递当前药单所有药品信息
    @ViewById(R.id.main_toolbar)
    Toolbar main_toolbar;
    @ViewById(R.id.av_drugs_name)
    AutoCompleteTextView av_drugs_name;
    //药品规格
    @ViewById(R.id.unit)
    AutoCompleteTextView unit;
    //开始时间
    @ViewById(R.id.sw_birthday)
    LinearLayout sw_birthday;
    //如何服药
    @ViewById(R.id.tv_how)
    TextView tv_how;
    //服药周期
    @ViewById(R.id.starttime)
    TextView starttime;
    @ViewById
    LinearLayout layout;
    //已有药单传过来的时间
    @Extra
    String DataTime;
    @ViewById(R.id.tv_drugs_name)
    TextView tv_drugs_name;
    @ViewById(R.id.tv_statsTime)
    TextView tv_statsTime;
    @ViewById(R.id.tv_quantity)
    TextView tv_quantity;

    @Extra
    PrescriptionDayData.ListBean.PerscriptDetailListBean prescriptionDay;
    String doctorNameVal = "";

    @ViewById(R.id.bt_delete)
    Button bt_delete;

    //结束时间
    String periodEndTime = null;
    //包装
//    String packages = "";
    ArrayAdapter<String> doseAdapter;

    @AfterViews
    void init() {
        setSupportActionBar(main_toolbar);
        initToolbar();

        ViseLog.d("时间" + DataTime);
        tv_statsTime.setText(format.format(new Date()).substring(0, 10));
        initData();
        initView();
    }

    int userEdit = 8;

    @Override
    protected void initView() {

        ViseLog.d("克隆的时间" + DataTime);

        //修改药单初始化
        if (prescriptionDay != null) {

            if (prescriptionDay.getRName() != null && prescriptionDay.getRName().length() > 0) {
                doctorNameVal = prescriptionDay.getRName();
            }


            main_toolbar.setTitle("编辑药品");
            tv_drugs_name.setVisibility(View.VISIBLE);
            av_drugs_name.setVisibility(View.GONE);

            if (prescriptionDay.getPackages() != null && prescriptionDay.getPackages().length() > 0) {
                tv_quantity.setText(prescriptionDay.getPackages());

                ViseLog.d("药品的包装名称" + prescriptionDay.getPackages());
            } else {
                tv_quantity.setText("单次量");
            }

            //药品名称
            if (prescriptionDay.getMName() != null) {
                av_drugs_name.setText(prescriptionDay.getMName());
                //赋予药品名称id
                medicineId = prescriptionDay.getMid();
                tv_drugs_name.setText(prescriptionDay.getMName());
            }

            //结束时间
            if (prescriptionDay.getPeriodEnd() != null) {
                periodEndTime = prescriptionDay.getPeriodEnd();
            }

            //药品规格
            if (prescriptionDay.getDoseName() != null) {
                unit.setText(prescriptionDay.getDoseName());
                isdoseName = prescriptionDay.getDoseName();
            }

            //开始时间
            if (prescriptionDay.getPeriodBegin() != null) {
                tv_statsTime.setText(prescriptionDay.getPeriodBegin().substring(0, 10));
            }

            //药品详情
            if (prescriptionDay.getPrescriptionDoseDetail() != null && prescriptionDay.getPrescriptionDoseDetail().size() > 0) {

                List<PrescriptionDayData.ListBean.PerscriptDetailListBean.PrescriptionDoseDetailBean>  perscriptDetailListBeen=new ArrayList<>();
                perscriptDetailListBeen.addAll(prescriptionDay.getPrescriptionDoseDetail());
                Collections.sort(perscriptDetailListBeen, new Comparator<PrescriptionDayData.ListBean.PerscriptDetailListBean.PrescriptionDoseDetailBean>() {
                    @Override
                    public int compare(PrescriptionDayData.ListBean.PerscriptDetailListBean.PrescriptionDoseDetailBean o1, PrescriptionDayData.ListBean.PerscriptDetailListBean.PrescriptionDoseDetailBean o2) {
                        Date date1 = DateUtil.stringToDate(o1.getUseTime());
                        Date date2 = DateUtil.stringToDate(o2.getUseTime());
                        if (date1.after(date2)) {
                            return 1;
                        }
                        return -1;
                    }
                });

                for (int i = 0; i < perscriptDetailListBeen.size(); i++) {
                    AlarmTime alarmTime = new AlarmTime();
                    if (UrlUtils.StrNum(perscriptDetailListBeen.get(i).getUseCount() + "")) {
                        alarmTime.unit = Float.parseFloat(perscriptDetailListBeen.get(i).getUseCount() + "");//剂量
                    }
                    //药品id
                    alarmTime.setId(perscriptDetailListBeen.get(i).getId() + "");
                    String Time = perscriptDetailListBeen.get(i).getUseTime();
                    int hour = Integer.parseInt(Time.substring(11, 13));
                    int min = Integer.parseInt(Time.substring(14, 16));
                    ViseLog.d("时" + Time.substring(11, 13) + "分" + Time.substring(14, 16) + "--" + perscriptDetailListBeen.get(i).getUseTime());
                    alarmTime.setTime(hour, min);
                    alarm.add(alarmTime);
                    StringBuffer stringBuffer = new StringBuffer();
                    stringBuffer.append(perscriptDetailListBeen.get(i).getUseTime().substring(11, 16));
                    strings.add(stringBuffer.toString());
                }
            }

            //如何服药
            if (prescriptionDay.getUseTypeId() != null) {
                isdoseMode = prescriptionDay.getUseTypeId();
                for (int i = 0; i < doseModeList.size(); i++) {
                    if (doseModeList.get(i).getPrimaryid() == Integer.parseInt(prescriptionDay.getUseTypeId())) {
                        doseModedb = doseModeList.get(i);
                        fsdoseMode = doseModeList.get(i).getPrimaryid() + "";
                        olddoseModename = doseModedb.getName();
                        tv_how.setText(doseModedb.getName());
                        ViseLog.d("如何服药" + doseModedb.getName());
                        break;
                    }
                }
            }
            //服药天数
            if (prescriptionDay.getUserPeriodId() != 0) {
                isdosePeriod = prescriptionDay.getUserPeriodId() + "";
                for (int i = 0; i < dosePeriodList.size(); i++) {
                    if (dosePeriodList.get(i).getPrimaryid() == prescriptionDay.getUserPeriodId()) {
                        starttime.setText(dosePeriodList.get(i).getName());
                        olddosename = dosePeriodList.get(i).getName();
                        fsdosePeriod = dosePeriodList.get(i).getPrimaryid() + "";
                        ViseLog.d("执行天数" + dosePeriodList.get(i).getPrimaryid());
                        dosePeriodInfo = dosePeriodList.get(i);

                        if (prescriptionDay.getUserPeriodId() == userEdit) {
                            ViseLog.d("自定义的服药天数呢" + dosePeriodList.get(i).getName());
                            starttime.setText(prescriptionDay.getTimeLen() + "天");
                        } else {
                            starttime.setText(dosePeriodList.get(i).getName());
                        }
                        timeLen = dosePeriodList.get(i).getTimelen();
                        break;
                    }
                }
            }


            if (prescriptionDay.getTimeLen() != null && prescriptionDay.getTimeLen().length() > 0) {
                timeLen = prescriptionDay.getTimeLen();
            }
            bt_delete.setVisibility(View.VISIBLE);

            if (prescriptionDay.getPackages() != null) {
                getPackages = prescriptionDay.getPackages();
            }
        } else {
            main_toolbar.setTitle("新增药品");
            tv_drugs_name.setVisibility(View.GONE);
            av_drugs_name.setVisibility(View.VISIBLE);
            AddDrugs();
            for (int i = 0; i < doseModeList.size(); i++) {
                if (doseModeList.get(i).getName().equals("每天服用")) {
                    doseModedb = doseModeList.get(i);
                    tv_how.setText(doseModedb.getName());
                    break;
                }
            }

            for (int i = 0; i < dosePeriodList.size(); i++) {
                if (dosePeriodList.get(i).getName().equals("长期")) {
                    dosePeriodInfo = dosePeriodList.get(i);
                    starttime.setText(dosePeriodInfo.getName());
                    timeLen = dosePeriodInfo.getTimelen();
                    break;
                }
            }
        }

        showitems();
    }

    @Override
    protected void initData() {
        medicineInfoList = MainAppliaction.getInstance().getMedicineInfoList();

        //服药方式转换
        doseModeList.addAll(MainAppliaction.getInstance().getDoseModeList());
        record_doseMode = new String[doseModeList.size()];
        for (int i = 0; i < doseModeList.size(); i++) {
            record_doseMode[i] = doseModeList.get(i).getName();
        }

        //服药周期
        dosePeriodList.addAll(MainAppliaction.getInstance().getDosePeriodList());
        dosePeriod = new String[dosePeriodList.size()];
        for (int i = 0; i < dosePeriodList.size(); i++) {
            dosePeriod[i] = dosePeriodList.get(i).getName();
        }

        prescriptionPresenter = new PrescriptionPresenter(this);
    }

    public void showitems() {
        layout.removeAllViews();
        List<AlarmTime> alarmItems = alarm.getTimes();
        for (int i = 0; i < alarmItems.size(); i++) {
            AlarmTime alarmItem = alarmItems.get(i);
            alarmItem.name = "第" + (i + 1) + "次";
            Widget_Alarm_Item item = new Widget_Alarm_Item(this);
            item.setItem(alarmItem);
            item.setRemove(this);
            layout.addView(item);
        }
    }

    // 药品信息筛选
    public void AddDrugs() {
        //药品的adapter
        medicineAdapter = new ArrayAdapter<MedicineInfodb>(this, android.R.layout.simple_list_item_1, medicineInfoList);
        //药品的adapter
        av_drugs_name.setAdapter(medicineAdapter);
        //选中事件
        av_drugs_name.setOnItemClickListener(this);
        //文字改变事件
        av_drugs_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String input = editable.toString() + "";
                if (input.length() > 0) {
                    showList(input);
                }
            }
        });
    }

    //根据输入的药品名称进行模糊查询
    private void showList(String input) {

        String abc1 = input;
        abc1 = abc1.replaceAll("\\(|\\)", "").replaceAll("（", "").replaceAll("）", "")
                .replaceAll("\\{|\\}", "").replaceAll("\\[|\\]", "");

        ViseLog.d("去除文字中的括号" + abc1);

        List<String> newlist = new ArrayList<String>();
        for (int x = 0; x < medicineInfoList.size(); x++) {
            if (medicineInfoList.get(x).getName().matches("(.*)" + abc1 + "(.*)")) {
                medicineAdapter.add(medicineInfoList.get(x));
                newlist.add(medicineInfoList.get(x).getName());
                ViseLog.d("去除文字中的括号+++" + medicineInfoList.get(x).getName());
            }
        }
        if (newlist.size() > 0) {
            //更新Adapter
            Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, removeDuplicate(newlist));
            av_drugs_name.setFocusable(true);
            av_drugs_name.setAdapter(Adapter);
            av_drugs_name.showDropDown();
            Adapter.notifyDataSetChanged();
        }
    }

    public static List removeDuplicate(List list) {
        HashSet h = new HashSet(list);
        list.clear();
        list.addAll(h);
        return list;
    }


    public void doseTiele(String name) {

        List<String> doselist = new ArrayList<>();
        List<MedicineInfodb> listdose = new ArrayList<>();
        if (name != null) {
            listdose.addAll(DataSupport.where("name=?", name).find(MedicineInfodb.class));
            for (int b = 0; b < listdose.size(); b++) {
                doselist.add(listdose.get(b).getDoses());
            }
        }

        if (doselist.size() > 0) {
            ViseLog.d(doselist.size());

            if (doselist.size() > 1) {
                doseAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, doselist);
                unit.setAdapter(doseAdapter);
                unit.showDropDown();
            } else {
                unit.setText(doselist.get(0));
            }

        }
    }


    String Name;

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //选择的是药物名称
        String medicineName = av_drugs_name.getText().toString();

        //判断数据是否存在
        if (beanList != null) {

            alarm.clearList();
            strings.clear();
            showitems();
            for (int i = 0; i < beanList.size(); i++) {

                allprescriptionDataBean = beanList.get(i);
                //名称相等显示出来
                if (medicineName.equals(beanList.get(i).getPer_name())) {
                    main_toolbar.setTitle("编辑药单");
                    av_drugs_name.setText(beanList.get(i).getPer_name());
                    Name = beanList.get(i).getPer_name();
                    medicineId = Integer.parseInt(beanList.get(i).getmID());
                    getTimeLen = beanList.get(i).getTimeLen();
                    //显示剂量信息
                    getID = beanList.get(i).getId();
                    getPackages = beanList.get(i).getPackages();
                    getPlid = beanList.get(i).getPlId();
                    timeLen = beanList.get(i).getTimeLen();
                    isdoseName = beanList.get(i).getDoseName();
                    tv_statsTime.setText(beanList.get(i).getStartTime().substring(0, 10));
//                    packages = beanList.get(i).getPackages();

                    doseTiele(medicineName);


                    if (getPackages != null && getPackages.length() > 0) {
                        tv_quantity.setText(getPackages);
                    } else {
                        tv_quantity.setText("单次量");
                    }
                    //如何服药
                    if (beanList.get(i).getUseTypeId() != null) {
                        for (int doseModei = 0; doseModei < doseModeList.size(); doseModei++) {
                            if (doseModeList.get(doseModei).getPrimaryid() == Integer.parseInt(beanList.get(i).getUseTypeId())) {

                                fsdoseMode = doseModeList.get(doseModei).getPrimaryid() + "";
                                olddoseModename = doseModedb.getName();
                                isdoseMode = beanList.get(i).getUseTypeId();
                                doseModedb = doseModeList.get(doseModei);
                                tv_how.setText(doseModedb.getName());
                                ViseLog.d("如何服药" + beanList.get(i).getUseTypeId());
                                break;
                            }
                        }
                    }
                    //服药天数
                    if (beanList.get(i).getUserPeriodId() != null) {
                        for (int dosea = 0; dosea < dosePeriodList.size(); dosea++) {
                            if (dosePeriodList.get(dosea).getPrimaryid() == Integer.parseInt(beanList.get(i).getUserPeriodId())) {
                                isdosePeriod = beanList.get(i).getUserPeriodId();
                                olddosename = dosePeriodList.get(dosea).getName();
                                fsdosePeriod = dosePeriodList.get(dosea).getPrimaryid() + "";
                                getPackages = medicineInfoList.get(i).getPackages();

                                if (dosePeriodList.get(dosea).getPrimaryid() == 8) {
                                    timeLen = beanList.get(i).getTimeLen();
                                } else {
                                    timeLen = dosePeriodList.get(dosea).getTimelen();
                                }

                                starttime.setText(dosePeriodList.get(dosea).getName());
                                ViseLog.d("执行天数" + beanList.get(i).getUserPeriodId());
                                dosePeriodInfo = dosePeriodList.get(dosea);
                                break;
                            }
                        }
                    }
                    int nums = beanList.get(i).getPrescriptionDoseDetail().size();

                    List<AllprescriptionDataBean.PrescriptionDoseDetailBean> prescriptionDoseDetailBeanList=new ArrayList<>();

                    for(int a=0;a<nums;a++){
                        prescriptionDoseDetailBeanList.add(beanList.get(i).getPrescriptionDoseDetail().get(a));
                    }

                    Collections.sort(prescriptionDoseDetailBeanList, new Comparator<AllprescriptionDataBean.PrescriptionDoseDetailBean>() {
                        @Override
                        public int compare(AllprescriptionDataBean.PrescriptionDoseDetailBean o1,AllprescriptionDataBean.PrescriptionDoseDetailBean o2) {
                            Date date1 = DateUtil.stringToDate(o1.getUseTime());
                            Date date2 = DateUtil.stringToDate(o2.getUseTime());
                            if (date1.after(date2)) {
                                return 1;
                            }
                            return -1;
                        }
                    });

                    //显示服药详情信息
                    for (int a = 0; a < nums; a++) {
                        AlarmTime alarmTime = new AlarmTime();
                        if (UrlUtils.StrNum(prescriptionDoseDetailBeanList.get(a).getUseCount() + "")) {
                            alarmTime.unit = Float.parseFloat(prescriptionDoseDetailBeanList.get(a).getUseCount() + "");//剂量
                        }
                        alarmTime.setId(prescriptionDoseDetailBeanList.get(a).getId() + "");
                        String Time = prescriptionDoseDetailBeanList.get(a).getUseTime();
                        int hour = Integer.parseInt(Time.substring(11, 13));
                        int min = Integer.parseInt(Time.substring(14, 16));
                        getPackages = beanList.get(i).getPackages();
                        alarmTime.setTime(hour, min);
                        alarm.add(alarmTime);
                        StringBuffer stringBuffer = new StringBuffer();
                        stringBuffer.append(stringBuffer.append(Time.substring(11, 16)));
                        strings.add(stringBuffer.toString());
                    }
                    showitems();
                    break;
                } else {
                    for (int a = 0; a < medicineInfoList.size(); a++) {
                        if (medicineInfoList.get(a).getName().equals(medicineName)) {
                            medicineId = medicineInfoList.get(a).getPrimaryid();
                            //根据输入的药品名称进行查询药品规格
                            doseTiele(medicineName);
                            medicineInfo = medicineInfoList.get(a);
                            getPackages = medicineInfoList.get(a).getPackages();

                            if (medicineInfoList.get(a).getPackages() != null && medicineInfoList.get(a).getPackages().length() > 0) {
                                tv_quantity.setText(medicineInfoList.get(a).getPackages());
                            } else {
                                tv_quantity.setText("单次量");
                            }

                            break;
                        }
                    }
                }
            }
        } else {
            alarm.clearList();
            strings.clear();
            showitems();
            for (int a = 0; a < medicineInfoList.size(); a++) {
                if (medicineInfoList.get(a).getName().equals(medicineName)) {
                    medicineId = medicineInfoList.get(a).getPrimaryid();
                    //根据输入的药品名称进行查询药品规格
                    doseTiele(medicineName);
                    getPackages = medicineInfoList.get(a).getPackages();
                    medicineInfo = medicineInfoList.get(a);

                    if (medicineInfoList.get(a).getPackages() != null && medicineInfoList.get(a).getPackages().length() > 0) {
                        tv_quantity.setText(medicineInfoList.get(a).getPackages());
                    } else {
                        tv_quantity.setText("单次量");
                    }
                    break;
                }
            }
        }
//        else {
//            for (int i = 0; i < medicineInfoList.size(); i++) {
//                if (medicineInfoList.get(i).getName().equals(medicineName)) {
//                    medicineId = medicineInfoList.get(i).getPrimaryid();
//                    //根据输入的药品名称进行查询药品规格
//                    unit.setText(medicineInfoList.get(i).getDoses());
//                    medicineInfo = medicineInfoList.get(i);
//                    break;
//                }
//            }
//        }
        if (medicineId < 0) {
            return;
        }


    }


    //如何服药
    @Click(R.id.ll_how)
    public void ll_how() {
        SimpleDialog.Builder builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {
                int index = getSelectedIndex();
                fragment.dismiss();
                tv_how.setText("" + doseModeList.get(index).getName());
                doseModedb = doseModeList.get(index);
                fsdoseMode = doseModeList.get(index).getPrimaryid() + "";
                super.onPositiveActionClicked(fragment);
            }

            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {
                super.onNegativeActionClicked(fragment);
                fragment.dismiss();
            }
        };

        ((SimpleDialog.Builder) builder).items(record_doseMode, 0)//默认选中如何服药第一条数据
                .title("选择服药周期")
                .positiveAction("确认")
                .negativeAction("取消");
        DialogFragment fragment = DialogFragment.newInstance(builder);
        fragment.show(getSupportFragmentManager(), null);
    }

    //服药天数
    @Click(R.id.startlayout)
    public void startlayout() {
        SimpleDialog.Builder builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {
                super.onPositiveActionClicked(fragment);
                int index = getSelectedIndex();
                fragment.dismiss();
                starttime.setText("" + dosePeriodList.get(index).getName());
                dosePeriodInfo = dosePeriodList.get(index);
                fsdosePeriod = dosePeriodList.get(index).getPrimaryid() + "";
                timeLen = dosePeriodList.get(index).getTimelen();
                if (dosePeriodInfo.getTimelen().equals("-1")) {
                    customData();
                }
            }

            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {
                super.onNegativeActionClicked(fragment);
                fragment.dismiss();
            }
        };

        ((SimpleDialog.Builder) builder).items(dosePeriod, 0)//0表示初始选中第一个
                .title("选择服药天数")
                .positiveAction("确认")
                .negativeAction("取消");
        DialogFragment fragment = DialogFragment.newInstance(builder);
        fragment.show(getSupportFragmentManager(), null);


    }

    String timeLen = "";

    public void customData() {
        final EditText et = new EditText(this);
        et.setInputType(InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE);
        et.setKeyListener(DigitsKeyListener.getInstance("1234567890"));
        et.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
        new AlertDialog.Builder(this).setTitle("请输入服药天数")
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String str = et.getText().toString().trim();
                        if (str == null || str.length() == 0) {
                            msg("请输入服药天数");
                            timeLen = "-1";
                            return;
                        } else {
                            if (!str.matches("^[1-9]\\d*$")) {
                                msg("请输入正确天数");
                                starttime.setText("");
                                return;
                            } else {
                                istimelen = true;
                                starttime.setText(str + "天");
                                timeLen = str;
                            }
                        }
                    }
                })
//                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                        if (timeLen.equals("-1")) {//等于-1的时候为自定义天数
//                            ViseLog.d("服药的天数" + timeLen + "***" + dosePeriodInfo.getName());
//                            timeLen = "7";//7默认时间为长期
//                            starttime.setText("长期");
//                        }
//                    }
//                })
                .show();
    }


    //选择开始时间
    @Click(R.id.sw_birthday)
    public void sw_birthday() {
        Date date = null;
        if (date == null) {
            date = new Date();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int i, int i2, int i3) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.YEAR, i);
                calendar.set(Calendar.MONTH, i2);
                calendar.set(Calendar.DAY_OF_MONTH, i3);
                //开始时间
                String Time = format.format(calendar.getTime()).substring(0, 10);
                tv_statsTime.setText(Time);
            }
        }, year, month, day);

        //限制时间
//        DatePicker datePicker = datePickerDialog.getDatePicker();
//        datePicker.setMinDate(TimeZoneUtil.getStringToDate(format.format(new Date()), "yyyy-MM-dd"));

        datePickerDialog.setTitle("选择服药时间");
        datePickerDialog.show();
    }


    boolean isClick = false;
    //记录服药时间是否改变
    String msgtime = "";

    //提交
    @OptionsItem(R.id.action_submit)
    public void action_submit() {
        if (isClick) {
            return;
        }
        String drugsName = av_drugs_name.getText().toString().trim();
        if (drugsName == null || drugsName.length() == 0) {
            msg("药品名称不能为空");
            return;
        }

        //规格
        String specifications = unit.getText().toString().trim();
        if (specifications == null || specifications.length() == 0) {
            msg("规格不能为空");
            return;
        }

        //服药方式
        String modeVal = tv_how.getText().toString().trim();

        //服药方式
        if (doseModedb == null) {
            msg("请选择如何服药");
            return;
        }
        //服药时长
        if (dosePeriodInfo == null) {
            msg("请选择服药时长");
            return;
        }
        //当服药时长为-1的时候证明是自定义
        if (timeLen.equals("-1")) {
            msg("请选择自定义服药天数");
            return;
        }


        //药单信息发生变化的时候检测参数变化值
//        StringBuffer stringBuffer=new StringBuffer();
//        //修改了服药天数
//        if(prescriptionDay.getUserPeriodId()!=dosePeriodInfo.getPrimaryid()){
//            stringBuffer.append("服药"+dosePeriodInfo.getName());
//        }
//
//        //修改了服药方式
//        if(!prescriptionDay.getUseTypeId().equals(doseModedb.getPrimaryid()+"")){
//            stringBuffer.append(","+modeVal);//服药方式
//        }
//        ViseLog.d("修改的药品信息"+stringBuffer.toString());


        //服药周期详情
        List<Prescription> prescriptions = new ArrayList<>();
        int count = layout.getChildCount();
        if (count == 0) {
            msg("请添加药品详情");
            return;
        }
        showDialog();

        for (int i = 0; i < count; i++) {
            View view = layout.getChildAt(i);
            if (view instanceof Widget_Alarm_Item) {
                Widget_Alarm_Item x = (Widget_Alarm_Item) view;
                //获取药品时间
                //x.getItem().getHour();
                x.getItem().getDate();
                Prescription prescr = new Prescription();
                prescr.setCount(x.getItem().unit);
                prescr.setIndex(i + 1);

                if (x.getItem().getId() != null && x.getItem().getId().length() > 0) {
                    prescr.setId(prescr.getIndex());
                }
                prescr.setDoseTime(format.format(x.getItem().getDate()));
                prescriptions.add(prescr);


                ViseLog.d("药单---" + prescr.getCount() + "////" + prescr.getIndex() + "-----" + prescr.getId());

            }
        }


        json = JSON.toJSONString(prescriptions);
        msgtime = updateTime(prescriptions, drugsName);

        ViseLog.d("药单---" + json);

        //开始时间
        StringBuffer statsBuffer = new StringBuffer();
        statsBuffer.append(tv_statsTime.getText().toString().trim());
        if (statsBuffer != null && statsBuffer.length() > 0) {
            statsTimeBuffer.append(statsBuffer);
            statsTimeBuffer.append(" 00:00:00");
        }

        isClick = true;
        //根据传过来的DataTime先进行判断是都需要克隆
        if (DataTime != null) {
            String TimeCloneData = DataTime.substring(0, 10);
            if (!TimeCloneData.equals(format.format(new Date()).substring(0, 10))) {
                ViseLog.d("需要克隆" + TimeCloneData + "++++");
                ClonePrescription(
                        "",//医生id
                        TimeCloneData,
                        drugsName,
                        specifications); //结束时间
            } else {
                //先判断是新增还是修改药单
                if (prescriptionDay != null) {
                    //format.format(new Date()).substring(0, 10) + "修改药品" + drugsName + ",规格" + specifications;
                    String msg = null;
                    if (updateInfo(drugsName) != null && updateInfo(drugsName).length() > 0) {
                        msg = UpMessage(drugsName) + "\n" + updateInfo(drugsName);
                    } else {
                        msg = UpMessage(drugsName) + updateInfo(drugsName);
                    }
                    UpdatePrescription(
                            "",//医生id
                            prescriptionDay.getPlId() + "",//药单pdID,如果克隆则填写克隆Id,否则传递prescriptionDay.pdId
                            medicineId + "",//药品id
                            ConstantManger.userType + "",//用户类型
                            statsTimeBuffer.toString(),//开始时间
                            doseModedb.getPrimaryid() + "",//服药方式
                            dosePeriodInfo.getPrimaryid() + "",//服药时长
                            json,//json
                            msg,//修改的msg
                            prescriptionDay.getId() + "",//药单id
                            goToSelectPicture(Integer.parseInt(timeLen)),//结束时间
                            drugsName,//药品名称
                            specifications,//药品剂量
                            prescriptionDay.getPackages(),//量纲
                            doseModedb.getHowto(),//间隔天数
                            timeLen
                    );
                } else if (Name != null) {
                    //
                    String msg = null;
                    if (updateInfo(drugsName) != null && updateInfo(drugsName).length() > 0) {
                        msg = UpMessage(drugsName) + "\n" + updateInfo(drugsName);
                    } else {
                        msg = UpMessage(drugsName) + updateInfo(drugsName);
                    }


                    UpdatePrescription(
                            "",//
                            getPlid + "",//单pdID,如果克隆则填写克隆Id,否则传递prescriptionDay.pdId
                            medicineId + "",//品id
                            ConstantManger.userType,//用户类型
                            statsTimeBuffer.toString(),//开始时间
                            doseModedb.getPrimaryid() + "",//服药方式
                            dosePeriodInfo.getPrimaryid() + "",//服药时长
                            json,//json
                            msg,//修改的msg
                            getID + "",//单id
                            goToSelectPicture(Integer.parseInt(timeLen)),//结束时间
                            drugsName,//品名称
                            unit.getText().toString().trim(),//品剂量
                            getPackages,//量纲
                            doseModedb.getHowto(),//间隔天数
                            timeLen
                    );

                } else {
                    //新增
                    //添加记录信息 新增药品生成的msg消息、、format.format(new Date()).substring(0, 10) + " 新增药品" + drugsName + " ,规格" + specifications;
                    String Message = "新增" + drugsName + transformation(json, specifications);

                    addPrescription(
                            medicineId + "",
                            statsTimeBuffer.toString(),
                            doseModedb.getPrimaryid() + "",
                            dosePeriodInfo.getPrimaryid() + "",
                            json,
                            Message,
                            "",//医生id
                            "",//克隆id   新增不存在克隆id
                            goToSelectPicture(Integer.parseInt(timeLen)),//结束时间,
                            drugsName,
                            specifications,
                            getPackages,
                            doseModedb.getHowto(),
                            timeLen
                    );
                }
            }
        } else {
            //新增
            //添加记录信息 新增药品生成的msg消息 format.format(new Date()).substring(0, 10) + " 新增药品" + drugsName + " ,规格" +medicineInfo.getDoses();
            String Message = "新增" + drugsName + transformation(json, specifications);
            addPrescription(
                    medicineId + "",
                    statsTimeBuffer.toString(),
                    doseModedb.getPrimaryid() + "",
                    dosePeriodInfo.getPrimaryid() + "",
                    json,
                    Message,
                    "",//医生id
                    "",//克隆id   新增不存在克隆id
                    goToSelectPicture(Integer.parseInt(timeLen)),//结束时间,
                    drugsName,
                    specifications,
                    getPackages,
                    doseModedb.getHowto(),
                    timeLen
            );
        }

    }


    //判断当前药单的服药时间是否修改过
    public String updateTime(List<Prescription> prescriptions, String drugsName) {
        StringBuffer stringBuffer = new StringBuffer();
        //alarm
        int size = strings.size();
        int index = prescriptions.size();
        if (size != index) {
            //当集合改变后说明服药时间已经发生改变不用编写日志
//            stringBuffer.append("\n修改了"+drugsName+"药的服药时间");
        } else {
            for (int i = 0; i < prescriptions.size(); i++) {
                ViseLog.d("时间不相等修改了服药时间++++" + prescriptions.get(i).getDoseTime().substring(11, 16) +
                        "**" + strings.get(i));
                if (!prescriptions.get(i).getDoseTime().substring(11, 16).equals(strings.get(i))) {
                    stringBuffer.append("\n修改了" + drugsName + "的服药时间");
                    break;
                }
            }
        }
        return stringBuffer.toString();
    }


    //删除药单
    @Click(R.id.bt_delete)
    public void bt_delete() {
        Dialog.Builder builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {
                super.onPositiveActionClicked(fragment);
                showDialog();
                //医生id,药单id,操作的msg
                //添加记录信息 新增药品生成的msg消息
                String Message = "删除" + av_drugs_name.getText().toString();
                if (prescriptionDay != null) {
                    deletePrescription("", prescriptionDay.getId() + "", Message);
                }
            }

            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {
                super.onNegativeActionClicked(fragment);
            }
        };

        builder.title("确定删除该药品吗？")
                .positiveAction("确定")
                .negativeAction("取消");
        ((SimpleDialog.Builder) builder)
                .message("注：调整药单时请联系你的主治医生。");
        DialogFragment fragment = DialogFragment.newInstance(builder);
        if (this instanceof AppCompatActivity) {
            AppCompatActivity activity = this;
            fragment.show(activity.getSupportFragmentManager(), null);
        }
    }

    //计算结束时间
    private String goToSelectPicture(int position) {

        ViseLog.d("自定义的时间" + position);
//        return TimeZoneUtil.setDrugsStatetime(position,tv_statsTime.getText().toString().trim());
        if (istimelen) {
            return TimeZoneUtil.setDrugsStatetime(Integer.parseInt(starttime.getText().toString().trim().replace("天", "")), tv_statsTime.getText().toString().trim());
        } else {
            return TimeZoneUtil.setDrugsStatetime(position, tv_statsTime.getText().toString().trim());
        }
    }

    //增加药单信息
    @Click(R.id.addbt)
    public void addbt() {
        //获取目前添加了几次服药详情
        int count = layout.getChildCount();
//        AlarmTime item = new AlarmTime();
//        item.unit = 1;
//        item.setTime(hour, 0);
//
//        if(count==0){
//            hour = hour + 10;
//        }
//
//        if (hour > 23) {
//            hour = 9;
//        }
//        alarm.add(item);
        int add = 1;
        listLayout(count, add);

    }


    public void listLayout(int count, int delete) {
        List<AlarmTime> time = null;
        switch (count) {
            case 0:
                time = alarm.getTimes();
                AlarmTime items = new AlarmTime();
                if(time.size()!=0){
                    items.unit = time.get(0).unit;
                }else{
                    items.unit = 1;
                }
                items.setTime(8, 0);
                alarm.clearList();
                alarm.add(items);
                break;

            case 1:
                time = alarm.getTimes();
                AlarmTime item1 = new AlarmTime();
                item1.unit = time.get(0).unit;
                item1.setTime(9, 0);

                AlarmTime item2 = new AlarmTime();
                if(time.size()!=1){
                    item2.unit = time.get(1).unit;
                }else{
                    item2.unit = 1;
                }
                item2.setTime(21, 0);

                alarm.clearList();
                alarm.add(item1);
                alarm.add(item2);

                break;

            case 2:
                time = alarm.getTimes();
                AlarmTime item3 = new AlarmTime();
                item3.unit = time.get(0).unit;
                item3.setTime(8, 0);

                AlarmTime item4 = new AlarmTime();
                item4.unit = time.get(1).unit;
                item4.setTime(16, 0);


                AlarmTime item5 = new AlarmTime();
                if(time.size()!=2){
                    item5.unit = time.get(2).unit;
                }else{
                    item5.unit = 1;
                }

                item5.setTime(22, 0);

                alarm.clearList();
                alarm.add(item3);
                alarm.add(item4);
                alarm.add(item5);
                break;


            case 3:
                time = alarm.getTimes();
                AlarmTime item6 = new AlarmTime();
                item6.unit = time.get(0).unit;
                item6.setTime(8, 0);

                AlarmTime item7 = new AlarmTime();
                item7.unit = time.get(1).unit;
                item7.setTime(12, 0);


                AlarmTime item8 = new AlarmTime();
                item8.unit = time.get(2).unit;
                item8.setTime(18, 0);

                AlarmTime item9 = new AlarmTime();
                if(time.size()!=3){
                    item9.unit = time.get(3).unit;
                }else{
                    item9.unit = 1;
                }

                item9.setTime(22, 0);

                alarm.clearList();
                alarm.add(item6);
                alarm.add(item7);
                alarm.add(item8);
                alarm.add(item9);
                break;


        }

        if (delete != 0) {
            if (count > 3) {
                time = alarm.getTimes();
                AlarmTime item6 = new AlarmTime();
                item6.unit = time.get(count - 1).unit;
                item6.setTime(23, 0);
                alarm.add(item6);
            }
        }

        showitems();
    }


    /**
     * 删除药单
     *
     * @param doctorId    医生Id
     * @param id          药单Id
     * @param editMessage 删除Msg
     */
    public void deletePrescription(String doctorId, String id, String editMessage) {

        prescriptionPresenter.DeletePrescriptionData(doctorId,
                id,
                editMessage,
                deleteListPrescription());
    }


    //删除药品后拼接ListPrescription
    public String deleteListPrescription() {

        String yaoPinName = av_drugs_name.getText().toString().trim();
        StringBuffer stringBuffer = new StringBuffer();
        if (ListPrescription != null) {
            if (ListPrescription.getPerscriptDetailList() != null && ListPrescription.getPerscriptDetailList().size() > 0) {

                for (int i = 0; i < ListPrescription.getPerscriptDetailList().size(); i++) {
                    if (!ListPrescription.getPerscriptDetailList().get(i).getMName().equals(yaoPinName)) {
                        stringBuffer.append(ListPrescription.getPerscriptDetailList().get(i).getMName());
                        stringBuffer.append("\t每天" + ListPrescription.getPerscriptDetailList().get(i).getPrescriptionDoseDetail().size() + "次\n");
                    }
                }

            }
        }

        return stringBuffer.toString();
    }

    /**
     * 克隆药单
     *
     * @param doctorId  医生id
     * @param statsTime 开始时间
     */

    public void ClonePrescription(String doctorId, String statsTime, String mName, String doseName) {

        prescriptionPresenter.ClonePrescriptionData(
                doctorId,
                statsTime,
                mName,
                doseName
        );
    }

    /**
     * 修改药单信息
     *
     * @param doctorId
     * @param pdid
     * @param mid
     * @param editType
     * @param startTime
     * @param howtoUse
     * @param howLong
     * @param list
     * @param editMessage
     * @param id
     * @param periodEnd   String mName,
     *                    String doseName,
     *                    String packages,
     *                    String useInterval,
     */
    public void UpdatePrescription(String doctorId, String pdid,
                                   String mid, String editType,
                                   String startTime, String howtoUse,
                                   String howLong, String list,
                                   String editMessage,
                                   String id, String periodEnd, String mName,
                                   String doseName,
                                   String packages,
                                   String useInterval, String timeLen) {

        prescriptionPresenter.updatePrescriptionData(
                doctorId,
                pdid,
                mid,
                editType,
                startTime,
                howtoUse,
                howLong,
                list,
                editMessage + msgtime,
                id,
                periodEnd,
                mName,
                doseName,
                packages,
                useInterval,
                timeLen,
                Updateprescription(mName, list)
        );
    }


    //修改药单生成prescription数据

    public String Updateprescription(String medicineName, String list) {
        String yaoPinName = av_drugs_name.getText().toString().trim();
        StringBuffer stringBuffer = new StringBuffer();
        List<String> Strsize = JSON.parseArray(list, String.class);


        if (ListPrescription != null) {
            if (ListPrescription.getPerscriptDetailList() != null && ListPrescription.getPerscriptDetailList().size() > 0) {

                for (int i = 0; i < ListPrescription.getPerscriptDetailList().size(); i++) {
                    if (ListPrescription.getPerscriptDetailList().get(i).getMName().equals(yaoPinName)) {
                        ListPrescription.getPerscriptDetailList().remove(i);
                        break;
                    }
                }


                if (medicineName.length() > 0 && Strsize.size() != 0) {
                    stringBuffer.append(medicineName);
                    stringBuffer.append("\t每天" + Strsize.size() + "次\n");
                }


                for (int i = 0; i < ListPrescription.getPerscriptDetailList().size(); i++) {
                    stringBuffer.append(ListPrescription.getPerscriptDetailList().get(i).getMName());
                    stringBuffer.append("\t每天" + ListPrescription.getPerscriptDetailList().get(i).getPrescriptionDoseDetail().size() + "次\n");
                }

            }
        }


        if (beanList != null) {
            if (beanList != null && beanList.size() > 0) {

                for (int i = 0; i < beanList.size(); i++) {
                    if (beanList.get(i).getPer_name().equals(yaoPinName)) {
                        beanList.remove(i);
                        break;
                    }
                }

                if (medicineName.length() > 0 && Strsize.size() != 0) {
                    stringBuffer.append(medicineName);
                    stringBuffer.append("\t每天" + Strsize.size() + "次\n");
                }


                for (int i = 0; i < beanList.size(); i++) {
                    stringBuffer.append(beanList.get(i).getPer_name());
                    stringBuffer.append("\t每天" + beanList.get(i).getPrescriptionDoseDetail().size() + "次\n");
                }

            }
        }


        return stringBuffer.toString();
    }


    //拼接的prescription信息数据

    public String prescriptionVal(String medicineName, int medicineIdSize) {

        StringBuffer stringBuffer = new StringBuffer();
        if (medicineName.length() > 0 && medicineIdSize != 0) {
            stringBuffer.append(medicineName);
            stringBuffer.append("\t每天" + medicineIdSize + "次\n");
        }

        if (beanList != null) {
            if (beanList.size() > 0) {
                for (int i = 0; i < beanList.size(); i++) {
                    if (beanList.get(i).getPer_name() != null && beanList.get(i).getPer_name().length() > 0) {//药品名称
                        stringBuffer.append(beanList.get(i).getPer_name());
                        stringBuffer.append("\t每天" + beanList.get(i).getPrescriptionDoseDetail().size() + "次\n");
                    }
                }
            }
        }
        return stringBuffer.toString();
    }


    //新增药单
    public void addPrescription(String medicineId, String startTime, String howtoUse,
                                String howLong, String list,
                                String editMessage, String doctorId,
                                String id, String periodEnd, String mName, String doseName,
                                String packages, String useInterval, String timeLen) {

        List<String> Strsize = JSON.parseArray(list, String.class);

        prescriptionPresenter.AddPrescriptionData(
                medicineId,       //药品名称id x
                startTime,  //开始时间  statsTimeBuffer.toString(),
                howtoUse,// 如何服药id howIndex+"",
                howLong,//服药天数id DoseDay+"",
                list,       //药品内容 json,
                editMessage,    //新增药品的msg Message,
                doctorId,//医生的id
                id,//克隆id
                periodEnd,//结束时间 endTime,
                mName,//药品名称 drugName,
                doseName,//剂量名称 medicineInfo.getDoses(),
                packages, //单品包装 medicineInfo.getPackages(),
                useInterval,//时间间隔 "1"
                timeLen,//自定义时长
                prescriptionVal(mName, Strsize.size())
        );
    }


    @Override
    public void onSuccess(DataStateResult data) {
        dessDialog();
        UpdateEvent updateEvent = new UpdateEvent();
        updateEvent.type = ConstantManger.MYGUESS;
        EventBus.getDefault().post(updateEvent);
        finish();
    }

    @Override
    public void onError(String msg) {
        dessDialog();
        if (msg != null) {
            msg(msg);
        }
        isClick = true;
    }

    @Override
    public void onRefreshUI() {
        dessDialog();
    }

    @Override
    public void onClonePrescription(ClonePrescriptionData data) {
        if (data.getMsgCode().equals("0x00000000")) {
            TimeCloneDataId = data.getPiid();

            String drugsName = av_drugs_name.getText().toString().trim();
            if (drugsName == null || drugsName.length() == 0) {
                msg("药品名称不能为空");
                return;
            }

            //规格
            String specifications = unit.getText().toString().trim();
            if (specifications == null || specifications.length() == 0) {
                msg("规格不能为空");
                return;
            }

            //服药方式
            if (doseModedb == null) {
                msg("请选择如何服药");
                return;
            }
            //服药时长
            if (dosePeriodInfo == null) {
                msg("请选择服药时长");
                return;
            }

            //当服药时长为-1的时候证明是自定义
//            if (dosePeriodInfo.getTimelen().equals("-1")) {
//                msg("自定义");
//                return;
//            }

            //判断是修改还是新增
            if (prescriptionDay != null) {
                String msg = "";
                if (updateInfo(drugsName) != null && updateInfo(drugsName).length() > 0) {
                    msg = UpMessage(drugsName) + "\n" + updateInfo(drugsName);
                } else {
                    msg = UpMessage(drugsName) + updateInfo(drugsName);
                }
                UpdatePrescription(
                        "",//医生id
                        TimeCloneDataId + "",//药单pdID,如果克隆则填写克隆Id,否则传递prescriptionDay.pdId
                        medicineId + "",//药品id
                        ConstantManger.userType + "",//用户类型
                        statsTimeBuffer.toString(),//开始时间
                        doseModedb.getPrimaryid() + "",//服药方式
                        dosePeriodInfo.getPrimaryid() + "",//服药时长
                        json,//json
                        msg,//修改的msg
                        data.getNewId() + "",//药单id
                        goToSelectPicture(Integer.parseInt(timeLen)),//结束时间
                        drugsName,//药品名称
                        specifications,//药品剂量
                        prescriptionDay.getPackages(),//量纲
                        doseModedb.getHowto(),//间隔天数
                        timeLen

                );

            } else if (Name != null) {
                //
                String msg = "";
                if (updateInfo(drugsName) != null && updateInfo(drugsName).length() > 0) {
                    msg = UpMessage(drugsName) + "\n" + updateInfo(drugsName);
                } else {
                    msg = UpMessage(drugsName) + updateInfo(drugsName);
                }

                UpdatePrescription(
                        "",//
                        TimeCloneDataId + "",//单pdID,如果克隆则填写克隆Id,否则传递prescriptionDay.pdId
                        medicineId + "",//品id
                        ConstantManger.userType,//用户类型
                        statsTimeBuffer.toString(),//开始时间
                        doseModedb.getPrimaryid() + "",//服药方式
                        dosePeriodInfo.getPrimaryid() + "",//服药时长
                        json,//json
                        msg,//修改的msg
                        data.getNewId() + "",//单id
                        goToSelectPicture(Integer.parseInt(timeLen)),//结束时间
                        drugsName,//品名称
                        unit.getText().toString().trim(),//品剂量
                        getPackages,//量纲
                        doseModedb.getHowto(),//间隔天数
                        timeLen
                );

            } else {
                //将json转换成对象
                String Message = "新增" + drugsName + transformation(json, specifications);
                addPrescription(
                        medicineId + "",
                        statsTimeBuffer.toString(),
                        doseModedb.getPrimaryid() + "",
                        dosePeriodInfo.getPrimaryid() + "",
                        json,
                        Message,
                        "",//医生
                        TimeCloneDataId + "",//克隆id   新增不存在克隆id
                        goToSelectPicture(Integer.parseInt(timeLen)),
                        drugsName,
                        specifications,
                        getPackages,
                        doseModedb.getHowto(),
                        timeLen
                );
            }
        }
    }

    public String transformation(String json, String specifications) {

        String howlong = tv_how.getText().toString();

        String message = "";

        List<Prescription> prescriptions = JSON.parseArray(json, Prescription.class);

        StringBuffer stringBuffer = new StringBuffer();
//        for (int i = 0; i < prescriptions.size(); i++) {
//            stringBuffer.append("\n\t\t\t"+prescriptions.get(i).getDoseTime().substring(10, 16) + ",");
//            stringBuffer.append(prescriptions.get(i).getCount());
//            stringBuffer.append("*" + specifications + "\t");
//        }
        stringBuffer.append("," + howlong + "\t每天服用" + prescriptions.size() + "次");
        message = stringBuffer.toString();

        return message;

    }
    //List<Prescription> prescriptions = new ArrayList<>();

    @Override
    public void onDeletePrescription(DataStateResult data) {
        if (data.getMsgCode().equals("0x00000000")) {
            UpdateEvent updateEvent = new UpdateEvent();
            updateEvent.type = ConstantManger.MYGUESS;
            EventBus.getDefault().post(updateEvent);
            finish();
        }
        dessDialog();
    }

    //判断服药详情是否存在修改
    public String updateInfo(String drugsName) {

        StringBuffer stringBuffer = new StringBuffer();
        int count = layout.getChildCount();
        if (prescriptionDay != null) {
            if (prescriptionDay.getPrescriptionDoseDetail().size() < count) {//说明新增了药品详情
                stringBuffer.append("修改" + drugsName + "\t" + "服药次数从" + prescriptionDay.getPrescriptionDoseDetail().size() + "次修改为" + count + "次");
            } else if (prescriptionDay.getPrescriptionDoseDetail().size() > count) {//删除了服药详情
                stringBuffer.append("修改" + drugsName + "\t" + "服药次数从" + prescriptionDay.getPrescriptionDoseDetail().size() + "次修改为" + count + "次");
            } else {//判断 是否修改了服药详情
                stringBuffer.append("");
            }
        }
        return stringBuffer.toString();

    }

    @Override
    public void onUpPrescription(DataStateResult data) {
        if (data.getMsgCode().equals("0x00000000")) {
            UpdateEvent updateEvent = new UpdateEvent();
            updateEvent.type = ConstantManger.MYGUESS;
            EventBus.getDefault().post(updateEvent);
            finish();
        }
        dessDialog();
    }

    @Override
    public void remove(Widget_Alarm_Item item) {
        alarm.remove(item.getItem());
        layout.removeView(item);

        int count = layout.getChildCount() - 1;

        ViseLog.d("次数检查" + count);
        int delete = 0;
        listLayout(count, delete);

    }

    boolean istimelen = false;

    private String UpMessage(String drugsName) {


        //判断服药天数是否为自定义天数如果是则后面添加天
        StringBuffer Buffer = new StringBuffer();
        String numberDay = starttime.getText().toString().trim();
        if (numberDay != null && numberDay.length() > 0) {
            if (OutliersValues.editTextNum(numberDay)) {
                Buffer.append(numberDay + "天");
            } else {
                Buffer.append(numberDay);
            }
        }

        ViseLog.d(isdosePeriod + "---" + fsdosePeriod + "---" + olddoseModename + "--" + olddosename);
        StringBuffer stringBuffer = new StringBuffer();
        if ((!isdosePeriod.equals(fsdosePeriod)) && (!isdoseMode.equals(fsdoseMode)) && (!isdoseName.equals(unit.getText().toString().trim()))) {
            stringBuffer.append(
                    "修改" + drugsName + "\t从" + isdoseName + "改为" + unit.getText().toString().trim() + "\n" +
                            "修改" + drugsName + "\t从" + olddosename + "改为" + Buffer.toString() + "\n" +
                            "修改" + drugsName + "\t从" + olddoseModename + "改为" + tv_how.getText().toString().trim());
            return stringBuffer.toString()+medication(drugsName);
        } else if ((!isdosePeriod.equals(fsdosePeriod)) && (!isdoseMode.equals(fsdoseMode))) {

            stringBuffer.append(
                    "修改" + drugsName + "\t从" + olddosename + "改为" + Buffer.toString() + "\n" +
                            "修改" + drugsName + "\t从" + olddoseModename + "改为" + tv_how.getText().toString().trim());
            return stringBuffer.toString()+medication(drugsName);
        } else if ((!isdoseMode.equals(fsdoseMode)) && (!isdoseName.equals(unit.getText().toString().trim()))) {
            stringBuffer.append(
                    "修改" + drugsName + "\t从" + olddosename + "改为" + Buffer.toString() + "\n" +
                            "修改" + drugsName + "\t从" + olddoseModename + "改为" + tv_how.getText().toString().trim());
            return stringBuffer.toString()+medication(drugsName);
        } else if ((!isdosePeriod.equals(fsdosePeriod)) && (!isdoseName.equals(unit.getText().toString().trim()))) {
            stringBuffer.append(
                    "修改" + drugsName + "\t从" + olddosename + "改为" + Buffer.toString() + "\n" +
                            "修改" + drugsName + "\t从" + isdoseName + "改为" + unit.getText().toString().trim());
            return stringBuffer.toString()+medication(drugsName);
        } else {


            ViseLog.d("-------------------------" + isdoseName + unit.getText().toString().trim() + "---" + isdosePeriod + "**" + fsdosePeriod + "--" + isdoseMode + "...." + fsdoseMode
            );
            if (!isdoseName.equals(unit.getText().toString().trim())) {
                //判断是否修改规格
                ViseLog.d("判断是否修改规格");
                stringBuffer.append("修改" + drugsName + "\t从" + isdoseName + "改为" + unit.getText().toString().trim());
                return stringBuffer.toString()+medication(drugsName);
            } else if (!isdosePeriod.equals(fsdosePeriod)) {
                ViseLog.d("判断是否修改服药天数");
                stringBuffer.append("修改" + drugsName + "\t从" + olddosename + "改为" + Buffer.toString());
                return stringBuffer.toString()+medication(drugsName);
            } else if (!isdoseMode.equals(fsdoseMode)) {
                ViseLog.d("判断是否修改如何服药");
                stringBuffer.append("修改" + drugsName + "\t从" + olddoseModename + "改为" + tv_how.getText().toString().trim());
                return stringBuffer.toString()+medication(drugsName);
            } else if (isdosePeriod.equals(fsdosePeriod)) {
                if (istimelen) {
                    ViseLog.d("天数:" + fsdosePeriod);
                    stringBuffer.append("修改" + drugsName + "\t从" + olddosename + "天" + "改为" + starttime.getText().toString().trim());
                    return stringBuffer.toString()+medication(drugsName);
                }
            }
        }
        ViseLog.d("修改药品详情"+medication(drugsName));
        return stringBuffer.toString()+medication(drugsName);
    }

    /**
     * 检测是否修改了服药详情
     */


    //匹配到的药品信息
    AllprescriptionDataBean allprescriptionDataBean;

    public String medication(String drugsName) {

        List<String> strings = new ArrayList<>();
        int count = layout.getChildCount();
        for (int i = 0; i < count; i++) {
            View view = layout.getChildAt(i);
            if (view instanceof Widget_Alarm_Item) {
                Widget_Alarm_Item x = (Widget_Alarm_Item) view;
                strings.add(x.getItem().unit + "");
            }
        }

        StringBuffer stringBuffer=new StringBuffer();
        if (prescriptionDay != null) {
            if (strings.size() == prescriptionDay.getPrescriptionDoseDetail().size()) {

                for(int i=0;i<prescriptionDay.getPrescriptionDoseDetail().size();i++) {
                    if(!strings.get(i).equals(prescriptionDay.getPrescriptionDoseDetail().get(i).getUseCount()+"")){
                        stringBuffer.append("\n修改"+drugsName+"第"+(i+1)+"次由"+prescriptionDay.getPrescriptionDoseDetail().get(i).getUseCount()+
                        "改为"+strings.get(i)+"\t");
                    }
                }
                ViseLog.d("进入了prescriptionDay");
            }
        } else if (allprescriptionDataBean != null) {//匹配的药品
            if (strings.size() == allprescriptionDataBean.getPrescriptionDoseDetail().size()) {

                for(int i=0;i<allprescriptionDataBean.getPrescriptionDoseDetail().size();i++) {
                    if(!strings.get(i).equals(allprescriptionDataBean.getPrescriptionDoseDetail().get(i).getUseCount()+"")){
                        stringBuffer.append("\n修改第"+(i+1)+"次,由"+allprescriptionDataBean.getPrescriptionDoseDetail().get(i).getUseCount()+
                                "改为"+strings.get(i)+"\t");
                    }
                }
                ViseLog.d("allprescriptionDataBean");
            }
        }
        return stringBuffer.toString();
    }
}